package com.example.coursedesign.ui.notifications;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;

import com.example.coursedesign.R;
import com.example.coursedesign.ui.notifications.entity.FamilyMember;

import java.io.IOException;

public class AddFamilyMemberActivity extends AppCompatActivity {

    private static final int CAMERA_REQUEST = 100;
    private static final int GALLERY_REQUEST = 200;
    private static final int PERMISSION_REQUEST_CODE = 300;

    private EditText etUsername, etRelation, etTel;
    private RadioGroup rgGender;
    private ImageView ivAvatar;
    private Button btnSubmit, btnCamera, btnGallery;
    private Uri selectedImageUri = null; // 用于存储所选图片的 URI

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_family);

        etUsername = findViewById(R.id.et_username);
        etRelation = findViewById(R.id.et_relation);
        etTel = findViewById(R.id.et_tel);
        rgGender = findViewById(R.id.rg_gender);
        ivAvatar = findViewById(R.id.iv_avatar);
        btnSubmit = findViewById(R.id.btn_submit);
        btnCamera = findViewById(R.id.button_camera);
        btnGallery = findViewById(R.id.button_gallery);

        // 设置提交按钮点击事件
        btnSubmit.setOnClickListener(v -> submitForm());

        // 设置拍照按钮点击事件
        btnCamera.setOnClickListener(v -> checkPermissionsAndOpenCamera());

        // 设置相册按钮点击事件
        btnGallery.setOnClickListener(v -> openGallery());

        // 启用返回按钮
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }
    }

    private void checkPermissionsAndOpenCamera() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
        } else {
            openCamera();
        }
    }

    private void openCamera() {
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (cameraIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(cameraIntent, CAMERA_REQUEST);
        } else {
            Toast.makeText(this, "无法打开相机", Toast.LENGTH_SHORT).show();
        }
    }

    private void openGallery() {
        Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        if (galleryIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(galleryIntent, GALLERY_REQUEST);
        } else {
            Toast.makeText(this, "无法打开相册", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openCamera();
            } else {
                Toast.makeText(this, "请授予相机和存储权限", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == CAMERA_REQUEST && data != null) {
                Bundle extras = data.getExtras();
                Bitmap imageBitmap = (Bitmap) extras.get("data");
                ivAvatar.setImageBitmap(imageBitmap);
                // 你可以在这里保存图片到本地并获取其 URI
                // selectedImageUri = saveImageToStorage(imageBitmap);
            } else if (requestCode == GALLERY_REQUEST && data != null) {
                selectedImageUri = data.getData();
                try {
                    Bitmap imageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImageUri);
                    ivAvatar.setImageBitmap(imageBitmap);
                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(this, "无法加载图片", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    private void submitForm() {
        String name = etUsername.getText().toString();
        String relation = etRelation.getText().toString();
        String tel = etTel.getText().toString();
        String gender = ((RadioButton)findViewById(rgGender.getCheckedRadioButtonId())).getText().toString();
        String avatarUrl = selectedImageUri != null ? selectedImageUri.toString() : "default_avatar_url";

        FamilyMember newMember = new FamilyMember(
                0, // ID will be assigned by your database or backend service
                name,
                gender,
                relation,
                tel,
                avatarUrl
        );

        Intent resultIntent = new Intent();
        resultIntent.putExtra("new_member", newMember);
        setResult(RESULT_OK, resultIntent);
        finish(); // Close the activity and return to MainActivity
    }

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed(); // 返回上一个 Activity
        return true;
    }
}